<template>
  <div class="roles">
    <!-- 面包屑导航开始 -->
    <el-breadcrumb separator="/" class="crumbs mt-15">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航结束 -->

    <!-- 添加角色开始 -->
    <el-button type="primary" plain class="mt-15" @click='addRole'>添加角色</el-button>
    <!-- 对话框 -->
    <el-dialog :title="titleInfo" :visible.sync="dialogVisible" width="40%" :before-close="hlose">
      <el-form :model="ruleForm" :rules="myrules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名字" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色结束 -->

    <!-- 表格开始 -->
    <el-table :data="tableData" style="width: 100%" border class="mt-15">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row v-if='scope.row.children.length===0'>该用户还未分配权限,请前往分配</el-row>
          <el-row v-else v-for='firstItem in scope.row.children' :key='firstItem.id'>
            <el-col :span="4">
              <el-tag closable @close="handleClose(scope.row,firstItem.id)">{{firstItem.authName}}</el-tag>
              <i class="el-icon-arrow-right"></i>
            </el-col>
            <el-col :span=" 20">
              <el-row v-for='lastItem in firstItem.children' :key='lastItem.id'>
                <el-col :span="4">
                  <el-tag type="success" closable @close="handleClose(scope.row,lastItem.id)">{{firstItem.authName}}</el-tag>
                  <i class="el-icon-arrow-right"></i>
                </el-col>
                <el-col :span="20">
                  <el-tag type="warning" class="warning" closable v-for="warItem in lastItem.children" :key='warItem.id' @close="handleClose(scope.row,warItem.id)">{{warItem.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column label="角色名称" prop="roleName">
      </el-table-column>
      <el-table-column label="描述" prop="roleDesc">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button class='edit' type="primary" icon="el-icon-edit" @click='editinfo(scope.row)'></el-button>
          <el-button class='edit' type="warning" icon="el-icon-delete" @click='deleteinfo(scope.row)'></el-button>
          <el-button class='edit' type="success" icon="el-icon-check" @click='treeRole(scope.row)'></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格开结束 -->

    <!-- tree开始 -->
    <el-dialog title="授权角色" :visible.sync="authorizationRole" width="40%" :before-close="handleClose">
      <el-tree :data="dataTree" show-checkbox node-key="id" default-expand-all :default-checked-keys="treeData" :props="defaultProps" class='trees' ref="tree">
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="callOf">取 消</el-button>
        <el-button type="primary" @click="sunmitRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- tree结束 -->
  </div>
</template>
<script>
import { rolesData, deleteAuth, addInfo, editsubmit, deleteRole, Rolelist, authEdit } from '@/api'
export default {
  data () {
    return {
      tableData: [], // 页面数据
      dialogVisible: false, // 添加角色弹出框
      authorizationRole: false, // 授权角色弹出框
      treeData: [], // 角色已有权限
      myrules: {
        roleName: [
          { required: true, message: '请输入角色名字', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在2 到 10 个字符', trigger: 'blur' }
        ]
      },
      ruleForm: {
        roleName: '',
        roleDesc: ''
      },
      titleInfo: '', // 会话框标题
      rows: {},
      dataTree: [

      ],
      defaultProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },

  created () {
    this.initData()
  },
  methods: {
    initData () {
      rolesData().then(res => {
        this.tableData = res.data
        console.log('初始化数据')
        console.log(res.data)

        // console.log(res.data)
      })
    },
    // 删除指定角色权限
    handleClose (row, rightId) {
      console.log(row.id, rightId)
      deleteAuth(row.id, rightId).then(res => {
        // 直接重置列表行数据 ,可以避免刷新再次请求数据,也能达到更新页面的效果
        row.children = res.data
        // this.initData()
      })
    },
    // 添加角色
    addRole () {
      this.titleInfo = '添加角色'
      this.dialogVisible = true
    },
    hlose (done) {
      done()
    },
    confirmAdd () {
      if (this.titleInfo === '添加角色') {
        this.$refs.ruleForm.validate(Pass => {
          if (Pass) {
            addInfo(this.ruleForm).then(res => {
              if (res.meta.status === 201) {
                this.dialogVisible = false
                this.titleInfo = ''
                // 编辑成功 重新刷新页面
                // this.$nextTick(() => {
                this.initData()
                // })
                this.$message.success('添加成功')
                // 添加完成以后清空
                this.ruleForm.roleName = ''
                this.ruleForm.roleDesc = ''
              }
              console.log(res)
            })
          } else {
            this.$error.success('添加失败')
            return false
          }
        })
      } else if (this.titleInfo === '编辑角色') {
        this.$refs.ruleForm.validate(Pass => {
          if (Pass) {
            editsubmit(this.rows.id, this.ruleForm).then(res => {
              console.log(res)
              if (res.meta.status === 200) {
                this.dialogVisible = false
                // 添加成功 重新刷新页面
                this.$nextTick(() => {
                  this.initData()
                })
                console.log(66)
                this.$message.success('编辑成功')
                console.log(res)
                this.ruleForm.roleName = ''
                this.ruleForm.roleDesc = ''
                this.titleInfo = ''
              }
            })
          } else {
            this.$error.success('编辑失败')
            this.ruleForm.roleName = ''
            this.ruleForm.roleDesc = ''
            this.titleInfo = ''
            return false
          }
        })
      }
    },
    cancel () {
      this.dialogVisible = false
      this.ruleForm.roleName = ''
      this.ruleForm.roleDesc = ''
      this.titleInfo = ''
    },

    // 编辑用户
    editinfo (row) {
      this.rows = row
      this.titleInfo = '编辑角色'
      this.dialogVisible = true
      console.log(this.titleInfo)

      // 编辑显示当前内容
      this.ruleForm.roleName = row.roleName
      this.ruleForm.roleDesc = row.roleDesc
    },
    // 删除角色
    deleteinfo (row) {
      deleteRole(row.id).then(res => {
        if (res.meta.status === 200) {
          this.$message.success('删除成功')
          this.initData()
        } else {
          this.$errror.error('删除失败')
        }
      })
    },
    // 授权角色
    treeRole (row) {
      this.rows = row
      this.authorizationRole = true
      // this.treeData = row.children
      // this.treeData = []
      Rolelist('tree')
        .then(res => {
          console.log(res)
          this.dataTree = res.data
          this.treeData.length = 0
          row.children.forEach(firstItem => {
            if (firstItem.children && firstItem.children.length > 0) {
              firstItem.children.forEach(lastItem => {
                if (firstItem.children && firstItem.children.length > 0) {
                  lastItem.children.forEach(endItem => {
                    this.treeData.push(endItem.id)
                  })
                }
              })
            }
          })
        })
      console.log(row)
    },
    sunmitRole () {
      console.log(this.rows.id)
      // 选中的节点
      let authid = this.$refs.tree.getCheckedKeys()
      // 半选中节点
      let CheckedKeys = this.$refs.tree.getHalfCheckedKeys()
      //  选中节点的合数组
      let chenckedAuth = [...authid, ...CheckedKeys]
      let idStrs = chenckedAuth.join(',')
      console.log(idStrs)
      // console.log(chenckedAuth.join(','))
      authEdit(this.rows.id, idStrs)
        .then(res => {
          if (res.meta.status === 200) {
            this.initData()
            this.authorizationRole = false

            this.$message.success(res.meta.msg)
          }
        })
    },
    callOf () {
      this.authorizationRole = false
      // this.treeData = []
    }
  }
}
</script>
<style lang="scss" scoped>
  .roles {
    .crumbs {
      padding: 15px;
    }
    .edit {
      padding: 8px 18px;
    }
    .el-icon-arrow-right {
      margin-left: 5px;
    }
    .el-col {
      margin-bottom: 10px;
    }
    .warning {
      margin-right: 15px;
    }
    .trees {
      height: 300px;
      overflow: auto;
    }
  }
</style>
